<template>
  <div ref="container" class="h-flow-variable-selector">
    <Tabs>
      <TabsPanel v-for="(item, index) in groups" :key="index" :tab="item.groupName">
        <ListSelector @dbselect="dbSelect" @select="select" :data-source="item.variables" :height="selectorHeight"/>
      </TabsPanel>
    </Tabs>
  </div>
</template>
<script>
import {Tabs} from 'ant-design-vue';
import ListSelector from '@/components/flow/ListSelector/ListSelector.vue';
import {createProps} from '@/utils/index.js';

export default {
  name: 'VariableSelector',
  components: {
    ListSelector,
    Tabs,
    TabsPanel: Tabs.TabPane,
  },
  props: {
    fieldGroups: createProps(Array, () => []),
    flowModel: createProps(Object),
    service: {
      type: Function,
      default: () => ({}),
    }
  },
  data() {
    return {
      selectorHeight: '200px',
      groups: [],
      dataSource: [],
    };
  },
  mounted() {
    this.loadVariables();
    this.bindResize();
  },
  beforeDestroy() {
    if (this.observer) {
      try {
        this.observer.unobserve();
      } catch (e) {
      }
      try {
        this.observer.disconnect();
      } catch (e) {
      }
      // console.log('取消监听了!')
    }
  },
  methods: {
    bindResize() {
      this.observer = new ResizeObserver(([{target}]) => {
        this.selectorHeight = `${target.offsetHeight - 55}px`
      });
      this.observer.observe(this.$refs.container.parentNode);
    },
    select(variable) {
      this.$emit('selectField', variable)
    },
    dbSelect(variable) {
      this.$emit('select', variable)
    },
    loadVariables() {
      this.service.get('/flow/variables/loadVariablesByFormType', {params: {formType: this.flowModel.formType}}).then(result => {

        if (this.fieldGroups && this.fieldGroups.length) {
          result = [...(result || []), ...this.fieldGroups];
        }
        this.groups = result;
        this.dataSource = result[0].variables;
      });
    },
  }
};
</script>
<style>
.h-flow-variable-selector .ant-tabs-top-bar {
  margin-bottom: 5px;
}

.h-flow-variable-selector {
  width: 550px;
}
</style>